/**
 * @file index.js
 * @description 路由配置文件
 * @created 2024-03-20
 */

import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import Manage from "../views/teacher/Manage.vue";
import Homework from "../views/teacher/Homework.vue";
import ChatView from "../views/teacher/ChatView.vue";
import Analysis from '../views/teacher/StudentAnalysis.vue'
import KnowledgeDataset from '@/views/teacher/KnowledgeDataset.vue';
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: () => import('@/views/Login.vue')
    },
    // 管理员路由
    {
      path: '/admin',
      component: () => import('@/views/admin/admin/AdminHome.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'home',
          name: 'AdminHomeOverview',
          component: () => import('@/views/admin/Home.vue'),
          meta: { requiresAuth: true, title: '学院管理概览', roles: ['school_admin', 'college_admin'] }
        },
        {
          path: 'college/:id',
          name: 'AdminCollegeDetail',
          component: () => import('@/views/admin/College.vue'),
          meta: { requiresAuth: true, title: '学院详情', roles: ['school_admin', 'college_admin'] },
        },
        {
          path: 'college/:collegeId/class/:classId',
          name: 'AdminClassDetail',
          component: () => import('@/views/admin/ClassDetail.vue'),
          meta: { requiresAuth: true, title: '班级详情', roles: ['school_admin', 'college_admin'] },
          props: true
        },
        {
          path: 'class/:collegeId/:gradeId/:classId',
          name: 'Class',
          component: () => import('@/views/admin/Class.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] },
          children: [
            {
              path: 'learning-analysis',
              name: 'LearningAnalysis',
              component: () => import('@/views/admin/analysis/LearningAnalysis.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            },
            {
              path: 'behavior-analysis',
              name: 'BehaviorAnalysis',
              component: () => import('@/views/admin/analysis/BehaviorAnalysis.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            },
            {
              path: 'warning-system',
              name: 'WarningSystem',
              component: () => import('@/views/admin/analysis/WarningSystem.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            }
          ]
        },
        {
          path: 'user',
          name: 'UserManagement',
          component: () => import('@/views/admin/UserManagement.vue'),
          meta: { requiresAuth: true, title: '用户管理', roles: ['school_admin'] }
        },
        {
          path: 'user/add',
          name: 'AddAdminUser',
          component: () => import('@/views/admin/admin/AddAdmin.vue'),
          meta: { requiresAuth: true, title: '添加用户', roles: ['school_admin'] }
        },
        {
          path: 'resources',
          name: 'ResourceManagement',
          component: () => import('@/views/admin/resources/YzhResourceManagement.vue'),
          meta: { requiresAuth: true, title: '资源管理', roles: ['school_admin', 'college_admin'] }
        },
        {
          path: 'innovative-teaching',
          name: 'InnovativeTeaching',
          component: () => import('@/views/admin/innovative/InnovativeTeaching.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] },
          children: [
            {
              path: 'ai-assistant',
              name: 'InnovativeAITeachingAssistant',
              component: () => import('@/views/admin/innovative/AITeachingAssistant.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            },
            {
              path: 'collaborative',
              name: 'CollaborativeLearning',
              component: () => import('@/views/admin/innovative/CollaborativeLearning.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            },
            {
              path: 'project-based',
              name: 'ProjectBasedLearning',
              component: () => import('@/views/admin/innovative/ProjectBasedLearning.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            },
            {
              path: 'evaluation',
              name: 'MultiDimensionalEvaluation',
              component: () => import('@/views/admin/innovative/MultiDimensionalEvaluation.vue'),
              meta: { requiresAuth: true, roles: ['school_admin', 'college_admin'] }
            }
          ]
        },
        {
          path: 'ai-decision',
          name: 'AIDecisionSystem',
          component: () => import('@/views/admin/ai/AIDecisionSystem.vue'),
          meta: { requiresAuth: true, title: 'AI决策辅助', roles: ['school_admin', 'college_admin'] }
        },
        {
          path: 'teacher',
          name: 'TeacherManagement',
          component: () => import('@/views/admin/teacheradmin/YzhTeachers.vue'),
          meta: { requiresAuth: true, title: '教师管理', roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
        {
          path: 'teacher/:teacherId',
          name: 'TeacherDetailShort',
          component: () => import('@/views/admin/teacheradmin/YzhTeacherDetail.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
        {
          path: 'teacher/:teacherId/detail',
          name: 'TeacherDetail',
          component: () => import('@/views/admin/teacheradmin/YzhTeacherDetail.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
        {
          path: 'teacher/:teacherId/course/:courseId/classes',
          name: 'TeacherCourseClasses',
          component: () => import('@/views/admin/teacheradmin/TeacherCourseClasses.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
        {
          path: 'teacher/:teacherId/course/:courseId/class/:classId/grades',
          name: 'ClassGrades',
          component: () => import('@/views/admin/teacheradmin/YzhClassGrades.vue'),
          meta: { requiresAuth: true, roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
        {
          path: 'ai-assistant',
          name: 'AIAssistantSystem',
          component: () => import('@/views/admin/ai/AIAssistantSystem.vue'),
          meta: { requiresAuth: true, title: '智能助手', roles: ['school_admin', 'college_admin', 'class_admin'] }
        },
      ]
    },
    // 教师路由
    {
      path: '/teacher',
      component: () => import('@/views/teacher/TeacherHome.vue'),
      meta: { role: 'teacher'},
      children: [
        // 教师子路由 不需要加/teacher/
        { path: "/teacher", redirect: "/manage" },
        { path: "/manage", component: Manage ,meta:{title:'教学资源管理'}},
        {
          path: "/homework",
          component: () => import('@/views/teacher/Homework.vue'),
          meta: { title: '作业管理' },
          children: [
            { path: "generation", component: () => import('@/components/Homework/AIQuestions.vue'), meta: { title: '题目生成' } },
            { path: "assignment", component: () => import('@/components/Homework/HomeworkAssignment.vue'), meta: { title: '作业布置' } },
            { path: "tracking", component: () => import('@/components/Homework/HomeworkTracking.vue'), meta: { title: '作业跟踪' } },
            { path: "correction", component: () => import('@/components/Homework/AICorrection.vue'), meta: { title: 'AI批改' } }
          ]
        },
        {
          path: "/chat/:botId",
          name: "Chat",
          component: ChatView,
          props: true,
          meta:{title:'智能体聊天'}
        },
        {
          path: "/chat",
          redirect: "/chat/default_bot"
        },
        { path: "/Analysis", component: Analysis ,meta:{title:'学生学情分析'}},
        { path: "/knowledge-dataset", component: KnowledgeDataset ,meta:{title:'知识库管理'}},
      ]
    },
    // 学生路由
    {
      path: '/student',
      name: 'student',
      component: () => import('@/views/student/StudentHome.vue'),
      meta: { role: 'student' },
      children: [
          {
              path: '',  // 路径改为空字符串，表示默认子路由
              redirect: { name: 'student' }
          },
          {
              path: 'Homepage/PersonalHomepage',
              name: 'PersonalHomepage',
              component: () => import('@/views/student/Homepage/PersonalHomepage.vue'),
              meta: {
                title: '个人主页'
              }
          },
          {
              path: 'Homepage/SelectedCourse',
              component: () => import('@/views/student/Homepage/SelectedCourse.vue')
          },
          {
              path: 'Homepage/PersonalData',
              component: () => import('@/views/student/Homepage/PersonalData.vue')
          },
          {
              path: 'Homepage/StudyPlan',
              component: () => import('@/views/student/Homepage/StudyPlan.vue')
          },
          // {
          //     path: 'Homepage/GeneralOption',
          //     component: () => import('@/views/student/Homepage/GeneralOption.vue')
          // },

      ]

    },
      {
          path:'/student/class',
          component: () => import('@/views/student/Class/StudentClass.vue')
      },
      {
          path: '/student/record/collect',
          name: 'collect',
          component:() => import('@/views/student/record/Collect.vue'),
          meta: {role: 'student'}
      },
      {
          path: '/student/record/note',
          name: 'note',
          component:() => import('@/views/student/record/Note.vue'),
          meta: {role: 'student'}
      },
      {
          path: '/student/edit-note',
          name: 'editNote',
          component:() => import('@/views/student/record/EditNote.vue'),
          meta: {role: 'student'}
      },
      {
          path: '/student/record/wrong',
          name: 'wrong',
          component:() => import('@/views/student/record/Wrong.vue'),
          meta: {role: 'student'}
      },
      {
          path: '/student/course/CourseSelect',
          component:() => import('@/views/student/course/CourseSelect.vue'),
          meta: {role: 'student'}
      },
      {
          path: '/student/course/:courseId',
          name: 'CourseStudy',
          component:() => import('@/views/student/course/CourseStudy.vue'),
          props: true,
          meta: {role: 'student'}
      },
      {
          path: '/student/course/Study',
          name: 'Study',
          component: () => import('@/views/student/course/Study.vue'),
          props: { courseId: '1' }, // 默认使用ID为1的课程
          meta: { role: 'student' }
      },
      {
          path: '/student/ai-teaching',
          name: 'AITeaching',
          component: () => import('@/views/student/AITeaching/AITeaching.vue'),
          meta: { role: 'student' }
      },
      {
          path: '/',
          name: 'CourseSelection',
          component: () => import('@/views/student/course/CourseSelect.vue'),
      },
      {
          path: '/courseDetail',
          name: 'CourseDetail',
          component: () => import('@/views/student/course/CourseDetail.vue'),
      },
      {
          path: '/student/project',
          component: () => import('@/views/student/project/StudentProject.vue'),
          name:'studentProject',
          meta: {role: 'student'},
          children: [
              {
                  path: '',  // 路径改为空字符串，表示默认子路由
                  redirect: {name: 'studentProject'}
              },
              {
                  path:'team',
                  component:() => import('@/views/student/project/StudentProjectTeam.vue'),
              },
              {
                  path: 'public',
                  component:() => import('@/views/student/project/StudentProjectPublic.vue')
              },
              {
                  path: 'personal',
                  component:() => import('@/views/student/project/StudentProjectPersonal.vue')
              }
          ]
      },
      {
          path:'/student/project/public',
          component:() => import('@/views/student/project/StudentProject.vue'),
          meta: { role: 'student' }
      },
      {
          path:'/student/project/task',
          component:() => import('@/views/student/project/StudentProject.vue'),
          meta: { role: 'student' }
      },
      {
          path:'/student/plan/PersonalPlan',
          component:() => import('@/views/student/plan/PersonalPlan.vue'),
          meta: { role: 'student' }
      },
  ]
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  console.log('路由跳转:', from.path, '->', to.path)
  console.log('当前用户状态:', {
    isLoggedIn: userStore.isLoggedIn,
    userRole: userStore.getUserRole,
  })

  if (to.path === '/login') {
    if (userStore.isLoggedIn) {
      console.log('已登录用户尝试访问登录页，重定向')
      // 根据角色重定向到各自的首页，避免循环
      if (userStore.getUserRole === 'school_admin' || userStore.getUserRole === 'college_admin') {
        next('/admin/home')
      } else if (userStore.getUserRole === 'class_admin') {
        next('/admin/teacher') // 班级管理员的默认页可能是教师管理
      } else if (userStore.getUserRole === 'teacher') {
        next('/teacher')
      } else if (userStore.getUserRole === 'student') {
        next('/student')
      } else {
        next('/') // 未知角色回主页
      }
    } else {
      next() // 未登录，允许访问登录页
    }
    return
  }

  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      ElMessage.error('请先登录')
      next({ path: '/login', query: { redirect: to.fullPath } })
    } else {
      const requiredRoles = to.meta.roles
      // 如果路由定义了允许的角色列表
      if (requiredRoles && Array.isArray(requiredRoles) && requiredRoles.length > 0) {
        const currentUserRole = userStore.getUserRole
        if (requiredRoles.includes(currentUserRole)) {
          next() // 用户角色符合要求，允许访问
        } else {
          ElMessage.error('您没有权限访问此页面')
          // 处理无权限：可以导航到上一个页面，或者一个特定的"无权限"页面，或者基于角色的默认首页
          // 避免循环重定向到from.path如果from.path也是无权限的
          if (from.name === 'Login' || !from.path || from.path === to.path ) {
            // 如果从登录页来，或没有来源，或目标和来源相同（可能直接输入URL），则导航到该角色的安全首页
            if (currentUserRole === 'school_admin' || currentUserRole === 'college_admin') {
              next('/admin/home')
            } else if (currentUserRole === 'class_admin') {
              // 班级管理员的默认可访问页面，例如教师管理
              if (to.path !== '/admin/teacher') next('/admin/teacher'); else next(false); //如果已在目标页，则不跳转
            } else {
              next('/'); // 其他角色回根路径
            }
          } else {
            next(false); // 阻止当前导航，停留在from.path
          }
        }
      } else {
        // 路由需要认证，但没有指定具体角色，则已登录用户均可访问
        next()
    }
  }
  } else {
    // 不需要认证的路由，直接放行
  next()
  }
})

export default router
